package com.client.koshercook.client;

import java.util.ArrayList;
import java.util.List;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
/** user favorites recipes */
public class UserFavorites extends RecsAndLinksBox {
	
	private List<String> lastResult = new ArrayList<String>();
	
	private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);
	
	public UserFavorites() {
		super("ספר המתכונים שלי");
		open.setUrl("favorites_off.gif");
		open.setSize("188px", "24px");
		open.addMouseOverHandler(new MouseOverHandler(){
			public void onMouseOver(MouseOverEvent event) {
				open.setUrl("favorites_on.gif");
			}
		});
		open.addMouseOutHandler(new MouseOutHandler(){
			public void onMouseOut(MouseOutEvent event) {
				open.setUrl("favorites_off.gif");
			}
		});
		open.setTitle("צפו ברשימת המתכונים המועדפים שלכם");
	}

	/** get the user information from the server */
	protected void getData() {
		greetingService.getUserFavorites(new AsyncCallback<List<String>>() {
			public void onFailure(Throwable caught) {
			}
			public void onSuccess(List<String> result) {
				for(String s : result)
					lastResult.add(s);
				fillTable(result);
				int i=1;
				for(String s : result){
					table.setWidget(i, 2, newRemoveFavoriteButton(s.substring(s.indexOf("@") + 1), s));
					table.getCellFormatter().addStyleName(i, 2,"IngListColums");
					i++;
				}
			}
		});
	}
	
	private Button newRemoveFavoriteButton(final String link, final String s){
		Button b = new Button("הסר");
		b.setTitle("לחץ כדי להסיר מתכון זה מספר המתכונים");
		b.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event) {
				greetingService.deleteUserFavorites(link, new AsyncCallback<Boolean>() {
					public void onFailure(Throwable caught) {
						Client.model.setInfoTextAndPO("תקלה בהסרת המתכון");
					}
					public void onSuccess(Boolean result) {
						Client.model.setInfoTextAndPO("מתכון הוסר מספר המתכונים בהצלחה");
						getData();
					}
				});
			}
		});
		return b;
	}
	
	protected void off(){
		open.setUrl("favorites_off.gif");
	}
}
